<?php
/**
 * Created by PhpStorm.
 * User: bob
 * Date: 2019/8/8
 * Time: 5:09 PM
 */

namespace App\Libs\Top;

use App\Api\PlanMarket\Models\OuterStores;
use App\Api\PlanMarket\Models\PlanOrderPages;
use App\Api\PlanMarket\Models\PlanOrders;
use App\Api\PlanMarket\Models\PlanOrdersLogs;
use App\Api\PlanMarket\Services\OrderService;
use App\Sdk\OuterStore\Tmall\AgisoClient;
use Carbon\Carbon;
use App\Sdk\Ali\TmallClient;

class TmallService
{
    protected $client;
    protected $shopName;

    function __construct($shopName)
    {
        $this->shopName = $shopName;
        $this->client = new TmallClient($shopName);
        $store = OuterStores::where('shop_name', '=', $shopName)
            ->where('source', '=', 'tmall')
            ->first();
        if (empty($store)) {
            throw new \LogicException('店铺不存在', 400);
        }
    }

    public function searchOrder()
    {
        $shopName = $this->shopName;
        $store = OuterStores::where('shop_name', '=', $shopName)
            ->first();
        $userId = data_get($store, 'user_id', '');
        $source = data_get($store, 'source', '');
        $flag = data_get($store, 'flag', '');
//        $startAt = data_get($store, 'fetch_start_at', Carbon::now()->subDays(10)->toDateTimeString());
//        $endAt = data_get($store, 'fetch_end_at', Carbon::now()->toDateTimeString());
//
        $startAt = Carbon::now()->subDays(30)->toDateTimeString();
        $endAt = Carbon::now()->toDateTimeString();
        $startAt = Carbon::parse($startAt)->timestamp.rand(100, 999);
        $endAt = Carbon::parse($endAt)->timestamp.rand(100, 999);



        info('天猫商铺抓单开始', [$shopName]);

        $page = 1;
        $pageSize = 15;
        do {
            $orders = $this->fetchOrdersId($startAt, $endAt, ['orderStatus' => 'PAID'], $page, $pageSize);
//            print_r($orders);exit;
//            sleep(2);
            $page++;
            info('外部抓单准备处理订单号', [$shopName, $startAt, $endAt, $orders]);
            foreach ($orders as $order) {
                $orderId = data_get($order, 'order_id', '');
                if (data_get(json_decode(get('http://91haoka.cn/api/plan-market/order/is-exist?outer_id='.$orderId.'&shop_id='.$userId)->getBody()->getContents(), 1), 'data', '0') == '1') {
                    info('外部商铺抓单订单号重复跳过', [$shopName, $userId, $orderId]);
                    continue;
                }
//                if (OrderService::isOrderExist($userId, $orderId)) {
//                    info('外部商铺抓单订单号重复跳过', [$shopName, $userId, $orderId]);
//                    continue;
//                }
                $sku = data_get($order, 'sku', '');

                if (empty($sku)) {
                    info('外部商铺抓单订单sku为空', [$shopName, $userId, $orderId]);
                    continue;
                }
                try {
                    $orderDetail = $this->orderDetail($orderId);
                    sleep(2);
                    info('外部抓单准备处理订单信息', [$shopName, $orderId, $orderDetail]);
                    $address = data_get($orderDetail, 'address', '');
                    $addressMobile = data_get($orderDetail, 'mobile', '');
                    $addressName = data_get($orderDetail, 'name', '');
                    $buyerMemo = data_get($orderDetail, 'buyer_memo', '');

                    $photos = $this->fetchPhoto($orderId);
                    info('外部抓单准备处理订单照片', [$shopName, $orderId, $photos]);
                    $idName = data_get($photos, 'name', '');
                    $idNum = data_get($photos, 'id_num', '');

                    $backUrl = data_get($photos, 'back_url', '');
                    $faceUrl = data_get($photos, 'face_url', '');
                    $handUrl = data_get($photos, 'hand_url', '');
                    $uploadPath = env('ID_CARD_PHOTO_PATH') . $idNum;
                    if (!\File::exists($uploadPath)) {
                        \File::makeDirectory($uploadPath);
                    }
                    $orderedAt = data_get($order, 'created_at', '');
                    $option = [
                        'source' => $source.'-'.$shopName,
                        'source_id' => $orderId,
                        'share_id' => $userId,
                        'mobile' => $addressMobile,
                        'name' => $addressName,
                        'id_name' => $idName,
                        'id_num' => $idNum,
                        'address' => $address,
                        'sku' => $sku,
                        'buyer_memo' => $buyerMemo,
                        'created_at' => $orderedAt,
                    ];
                    $r = post('http://91haoka.cn/api/plan-market/order/for-web/purchase-sku', $option)->getBody()->getContents();
                    info('天猫转发sku下单订单', [$option, $r]);
                    $j = json_decode($r, 1);

                    if (data_get($j,'msg.code') != 0) {
                        continue;
                    }
                    $plan_order_id = data_get($j,'data.id');//没走这 走的planordercreate
                    if ($plan_order_id) OrderService::updateOrder('',['id'=>$plan_order_id,'memo'=>'已抓单']);
//                   $end_memo   = $this->endMemo($orderId, '已抓单');
//                   $this->updateSellerMemo($orderId, $flag, $end_memo);
                   
                    if (empty($backUrl) || empty($faceUrl) || empty($handUrl)) {
                        continue;
                    }
                    $params = [
                        'str_rand' => base64_convert_encode(str_random(6) . '-' . $orderId . '-' . str_random(6), 64, 62),
                    ];
                    $multipart = [];
                    foreach ($params as $k => $param) {
                        $multipart[] = [
                            'name' => $k,
                            'contents' => $param,
                        ];
                    }
                    if (!file_exists(public_path('storage/upload/id_card_photo/'.$idNum))) {
                        mkdir(public_path('storage/upload/id_card_photo/'.$idNum));
                    }
                    $facePath = env('ID_CARD_PHOTO_PATH', base_path('public/storage/upload/id_card_photo/')).$idNum.'/face.jpg';
                    $handPath = env('ID_CARD_PHOTO_PATH', base_path('public/storage/upload/id_card_photo/')).$idNum.'/hand.jpg';
                    $backPath = env('ID_CARD_PHOTO_PATH', base_path('public/storage/upload/id_card_photo/')).$idNum.'/back.jpg';
                    file_put_contents($facePath, file_get_contents($backUrl));
                    file_put_contents($backPath, file_get_contents($faceUrl));
                    file_put_contents($handPath, file_get_contents($handUrl));
                    $multipart[] = [
                        'name' => 'pic[face]',
                        'contents' => fopen($facePath, 'r')
                    ];
                    $multipart[] = [
                        'name' => 'pic[back]',
                        'contents' =>  fopen($backPath, 'r')
                    ];
                    $multipart[] = [
                        'name' => 'pic[hand]',
                        'contents' =>  fopen($handPath, 'r')
                    ];

                    $r = \Guzzle::request('post', 'http://91haoka.cn/api/plan-market/order/photo/outer-upload', ['multipart' => $multipart])->getBody()->getContents();
                    info('天猫转发照片', [$params, $r]);
                } catch (\Exception $e) {
                    error('第三方商铺抓单异常', [$orderId, $source, $e->getMessage()]);
                    ding('soreport', '天猫抓单异常'.$orderId.$source.$e->getMessage());
                    continue;
                }
                try {
                    //通知京东已抓单  获取flag ，目前没抓  可能京东不是叫flag 现在就默认0
                  //  $end_memo   = $this->endMemo($orderId, '已抓单');
                   // $this->updateSellerMemo($orderId, $flag, $end_memo);
                } catch (\Exception $e) {
                    error('第三方商铺抓单后标记', [$orderId, $source, $e->getFile(), $e->getLine(), $e->getMessage()]);
                } catch (\Error $e) {
                    error('第三方商铺抓单后标记', [$orderId, $source, $e->getFile(), $e->getLine(), $e->getMessage()]);
                }
//                exit;
            }
        } while (count($orders) == $pageSize);
    }

    public function refreshCookie()
    {
        $o = PlanOrders::where('source', '=', 'tmall-'.$this->shopName)
            ->select('real_source_id')
            ->where('ordered_at', '!=', null)
            ->orderBy('id', 'desc')
            ->first();
        $oid = data_get($o, 'real_source_id', '');
        try {
            $r = $this->orderDetail($oid);
            info('天猫刷cookie', [$this->shopName, $oid, $r]);
        } catch (\Exception $e) {
            error('天猫刷cookie异常了', [$oid, $e->getMessage(), $e->getCode()]);
            if ($e->getCode() == '202' || strpos($e->getMessage(), 'redirects') ) {
                error('天猫抓单异常', [$this->shopName]);
                ding('soreport', '天猫抓单可能掉线了'.$this->shopName);
                OuterStores::where('shop_name', '=', $this->shopName)
                    ->where('source', '=', 'tmall')
                    ->update([
                        'logout_at' => Carbon::now()->toDateTimeString(),
                       // 'is_run' => 0,//wqtmall
                        //'is_login' => 0,//622只把cookie改为掉线，下次补抓仍会进来
                        'is_cookie' => 0,
                    ]);
                $store = OuterStores::where('source', '=', 'tmall')
                    ->where('shop_name', '=', $this->shopName)
                    ->first();
                $mobile = data_get($store, 'mobile', '');
                if (!empty($mobile) && !\Cache::has("client_{$mobile}_notified")) {
                    \Top::aliSendSms($mobile, '(天猫店)'.$this->shopName, 'client_warning');
                    \Cache::put("user_{$mobile}_notified", 1, 60);
                }
                throw new \LogicException('抓单异常', 102);
            }
        }

        return true;
        $r = $this->client->refreshCookie();
        $dom = new \simple_html_dom();
        $dom->load($r);
        $userName = data_get($dom->find('.sn-user-nick', 0), 'plaintext');

        if (!strstr($userName, $this->shopName)) {
            error('天猫抓单异常', [$this->shopName, $r]);
            ding('error', '天猫抓单可能掉线了'.$this->shopName);
            OuterStores::where('shop_name', '=', $this->shopName)
                ->where('source', '=', 'tmall')
                ->update([
                    'logout_at' => Carbon::now()->toDateTimeString(),
                    'is_run' => 0,
                    'is_login' => 0,
                ]);
            $store = OuterStores::where('source', '=', 'tmall')
                ->where('shop_name', '=', $this->shopName)
                ->first();
            $mobile = data_get($store, 'mobile', '');
            if (!empty($mobile) && !\Cache::has("client_{$mobile}_notified")) {
                \Top::aliSendSms($mobile, '(天猫店)'.$this->shopName, 'client_warning');
                \Cache::put("user_{$mobile}_notified", 1, 60);
            }
            throw new \LogicException('抓单异常', 102);
        }
        return true;
        $r = $this->client->isNeedAuth();
        if ($r != '{"isNeedAuth":"false"}') {
            error('天猫抓单异常', [$this->shopName, $r]);
            ding('error', '天猫抓单可能掉线了'.$this->shopName);
            OuterStores::where('shop_name', '=', $this->shopName)
                ->where('source', '=', 'tmall')
                ->update([
                    'logout_at' => Carbon::now()->toDateTimeString(),
                    'is_run' => 0,
                    'is_login' => 0,
                ]);
            $store = OuterStores::where('source', '=', 'tmall')
                ->where('shop_name', '=', $this->shopName)
                ->first();
            $mobile = data_get($store, 'mobile', '');
            if (!empty($mobile) && !\Cache::has("client_{$mobile}_notified")) {
                \Top::aliSendSms($mobile, '(天猫店)'.$this->shopName, 'client_warning');
                \Cache::put("user_{$mobile}_notified", 1, 60);
            }
            throw new \LogicException('抓单异常', 102);
        }
        return true;
        $shopName = $this->shopName;
        $startAt = Carbon::now()->subDays(1)->toDateTimeString();
        $endAt = Carbon::now()->toDateTimeString();

        $startAt = Carbon::parse($startAt)->timestamp.rand(100, 999);
        $endAt = Carbon::parse($endAt)->timestamp.rand(100, 999);

        info('天猫刷新cookie', [$shopName]);

        $page = 1;
        $pageSize = 15;
        $orders = $this->fetchOrdersId($startAt, $endAt, ['orderStatus' => 'PAID'], $page, $pageSize);
    }

    public function saveCancelOrder()
    {
        $shopName = $this->shopName;
        $store = OuterStores::where('shop_name', '=', $shopName)
            ->first();
        $userId = data_get($store, 'user_id', '');

        $startAt = Carbon::now()->subDays(20)->toDateTimeString();
        $endAt = Carbon::now()->toDateTimeString();
        info('天猫商铺抓取消单开始', [$shopName]);


        $page = 1;
        $pageSize = 15;
        do {
            $orders = $this->fetchOrdersId($startAt, $endAt, ['orderStatus' => 'DROP'], $page, 15);
            sleep(3);
            $page++;
            info('天猫抓取消单准备处理订单号', [$shopName, $orders]);
            foreach ($orders as $order) {
                $orderId = data_get($order, 'order_id', '');

                $planOrder = PlanOrders::where('share_id', '=', $userId)
                    ->where('status', '!=', config('store.ORDER_STATUS_V2.CLOSED.CODE'))
                    ->where('source_id', '=', $orderId)
                    ->first();

                if (empty($planOrder)) {
                    info('京东商铺抓取消单订单号不存在跳过', [$shopName, $userId, $orderId]);
                    continue;
                }

                $tmpSellerMemo = data_get($planOrder, 'seller_memo', '');

                $planOrder->update([
                    'status' => config('store.ORDER_STATUS_V2.CLOSED.CODE'),
                    'seller_memo' => $tmpSellerMemo . Carbon::now()->toDateTimeString() . '自动取消退款订单 ',
                    'reason' => '自动取消退款订单',
                ]);
            }
        } while (count($orders) == $pageSize);
    }

    public function fetchOrdersId($startAt, $endAt, $status, $page=1, $pageSize=15)
    {
        $r = $this->client->fetchOrder($startAt, $endAt, $status, $page, $pageSize);
//        info('天猫抓单返回', [$this->shopName, $startAt, $endAt, $status, $page, $pageSize, $r]);
        $j = json_decode($r, 1);
        if (!is_array($orders = data_get($j, 'mainOrders'))) {
            error('天猫抓单异常', [$this->shopName, $r]);
            ding('error', '天猫抓单可能掉线了'.$this->shopName);
            OuterStores::where('shop_name', '=', $this->shopName)
                ->where('source', '=', 'tmall')
                ->update([
                    'logout_at' => Carbon::now()->toDateTimeString(),
                    'is_run' => 0,
                    'is_login' => 0,
                ]);
            $store = OuterStores::where('source', '=', 'tmall')
                ->where('shop_name', '=', $this->shopName)
                ->first();
            $mobile = data_get($store, 'mobile', '');
            if (!empty($mobile) && !\Cache::has("client_{$mobile}_notified")) {
                \Top::aliSendSms($mobile, '(天猫店)'.$this->shopName, 'client_warning');
                \Cache::put("user_{$mobile}_notified", 1, 60);
            }
            throw new \LogicException('抓单异常', 102);
            preg_match("/var\ data\ =\ JSON.parse\('(.*)'\);/", $r, $arr);
            $r = data_get($arr ,'1');
            $r = str_replace('\\"', '"', $r);
            $r = str_replace('\\/', '/', $r);
            $j = json_decode($r, 1);
            $orders = data_get($j, 'mainOrders', '');
            if (!is_array($orders) || empty($orders)) {
                ding('error', '天猫抓单有问题');
                throw new \LogicException('抓单异常', 102);
            }
        }
        $return = [];
        foreach ($orders as $order) {
            $orderId = data_get($order, 'id');
            $createdAt = data_get($order, 'orderInfo.createTime');
            $sku = '';
            $orderExtra = data_get($order, 'subOrders.0.itemInfo.extra');
            if (is_array($orderExtra)) {
                foreach ($orderExtra as $extra) {
                    if (data_get($extra, 'name') == '商家编码') {
                        $sku = data_get($extra, 'value', '');
                    }
                }
            }

            $return[] = ['order_id' => $orderId, 'sku' => $sku, 'created_at' => $createdAt];
        }

        return $return;
    }

    public function orderDetail($orderId)
    {
        $r = $this->client->fetchOrderDetail($orderId);
//        print_r($r);exit;
        if (strstr($r, '扫码登录')) {
            $reason ='tmall详情cookie失效';
            PlanOrdersLogs::where('source_id', $orderId)
           ->update(['reason' =>$reason]);
            OuterStores::where('source', '=', 'tmall')
                ->where('shop_name', '=', $this->shopName)
                ->update(['is_cookie' =>0]);
            throw new \LogicException('cookie失效', 202);
        }
        preg_match('/var\ detailData\ =\ (.*)/', $r, $arr);

        $detailData = data_get($arr, '1', '');
        $detailJson = json_decode($detailData, 1);
        $detailLists = data_get($detailJson, 'basic.lists', []);
        //info('天猫抓取订单详情返回', [$orderId, $detailJson]);
        $addressMatch = '';
        $idNum = '';
        $idNum2 = '';
        $idName = '';
        $idName2 = '';
        $idName3 = '';
        $buyerMemoMatch = '';
        foreach ($detailLists as $k => $detailList) {
            if (data_get($detailList, 'key') == '收货地址') {
                $addressMatch = data_get($detailList, 'content.0.text', '');
            }
            if (data_get($detailList, 'key') == '买家留言') {
                $buyerMemoMatch = data_get($detailList, 'content.0.text', '');
            }
            if (data_get($detailList, 'key') == '身份证号') {
                $idNum = data_get($detailList, 'content.0.text', '');
            }
            if (data_get($detailList, 'key') == '证件号码') {
                $idNum2 = data_get($detailList, 'content.0.text', '');
            }
            if (data_get($detailList, 'key') == '机主姓名') {
                $idName = data_get($detailList, 'content.0.text', '');
            }
            if (data_get($detailList, 'key') == '姓  名') {
                $idName2 = data_get($detailList, 'content.0.text', '');
            }
            if (data_get($detailList, 'key') == '姓名') {
                $idName3 = data_get($detailList, 'content.0.text', '');
            }
        }

        $addressInfoArr = explode(',', $addressMatch);

        foreach ($addressInfoArr  as $key=> $address) {
            $addressInfoArr[$key]=strip_tags($address);
         
            }
        info('天猫抓单详情数组', [$addressInfoArr]);
        if(isset($addressInfoArr) and isset($addressInfoArr[1]) and isset($addressInfoArr[2])  and is_numeric(str_replace("-","",$addressInfoArr[1])) and is_numeric(str_replace("-","",$addressInfoArr[2]))){
            info('天猫抓单详情name重复', [$addressInfoArr]);  
            $address = data_get($addressInfoArr, '3', '');
            $name = data_get($addressInfoArr, '0', '');
            if(strstr($addressInfoArr[1], '86-')){
                $addressInfoArr[1] = str_replace('86-', '', $addressInfoArr[1]);
            };		
	        if(strstr($addressInfoArr[2], '86-')){
                $addressInfoArr[2] = str_replace('86-', '', $addressInfoArr[2]);
            };		 
	        if(preg_match("/^1[34578]{1}\d{9}$/",$addressInfoArr[1])){


               $mobile = $addressInfoArr[1];
            
            }else{
            
               $mobile = $addressInfoArr[2];
            
            }

            info('天猫抓单详情双手机号mobile', [$mobile]);      

        }elseif(isset($addressInfoArr[0]) and is_numeric(str_replace("-","",$addressInfoArr[1]))==false and is_numeric(str_replace("-","",$addressInfoArr[2]))){
            $address = data_get($addressInfoArr, '3', '');
            $mobile = data_get($addressInfoArr, '2', '');
            if(strstr($mobile, '86-')){
            $mobile = str_replace('86-', '', $mobile);
            info('天猫抓单详情双name手机号mobile', [$mobile]);   
            };
            $name = data_get($addressInfoArr, '0', '');
        }else{
        $address = data_get($addressInfoArr, '2', '');
        info('天猫抓单详情地址', [$address]);
        $mobile = data_get($addressInfoArr, '1', '');
        if(strstr($mobile, '86-')){
        $mobile = str_replace('86-', '', $mobile);
        info('天猫抓单详情单手机号mobile', [$mobile]);   
        };
        if(strstr($mobile, '61-')){
            $mobile = str_replace('61-', '', $mobile);
            info('天猫抓单详情单手机号mobile', [$mobile]);   
            };
        $name = data_get($addressInfoArr, '0', '');
      
        }

        if (empty($idName)) {
            $idName = $idName2;
        }
        if (empty($idName)) {
            $idName = $idName3;
        }
        if (empty($idNum)) {
            $idNum = $idNum2;
        }
        if($mobile==0432342152){
            $mobile=10432342152;
            $address='广东省东莞市沙田镇西大坦启盈国际快件中心递四方D集运仓';
            $name='Zhenhua Wang';
            info('天猫抓单详情name1', [$mobile,$name,$address]);
        }

        //preg_match('/1[\d]{10}/', $mobile, $tmp);
        //$mobile = data_get($tmp, '0', '');
        info('天猫抓单详情name', [$mobile,$name,$address]);
        if (empty($address) || empty($mobile) || empty($name)) {
            $reason ='天猫抓单获取订单详情没有获取到必要信息';
            PlanOrdersLogs::where('source_id', $orderId)
           ->update(['reason' =>$reason]);
            error('天猫抓单获取订单详情没有获取到必要信息', [$r]);
            throw new \LogicException('天猫抓单获取订单详情没有获取到必要信息', 203);
        }
        return [
            'address' => $address,
            'buyer_memo' => $buyerMemoMatch,
            'mobile' => trim($mobile),
            'name' => trim($name),
            'id_num' => trim($idNum),
            'id_name' => trim($idName),
        ];
    }

    public function fetchPhoto($orderId)
    {
        $r = $this->client->fetchPhoto($orderId);
        preg_match_all("/({.*})/", $r, $tmp);
        $res = data_get($tmp, '0.0', '');
        $json = json_decode($res, 1);

        $name = data_get($json, 'data.realName', '');
        $idNum = data_get($json, 'data.certNo');
        $pics = data_get($json, 'data.authPics', []);

        $picUrlBack = '';
        $picUrlFace = '';
        $picUrlHand = '';
        foreach ($pics as $pic) {
            if (data_get($pic, 'tag') == '身份证背面') {
                $picUrlBack = data_get($pic, 'url', '');
            }

            if (data_get($pic, 'tag') == '身份证正面') {
                $picUrlFace = data_get($pic, 'url', '');
            }

            if (data_get($pic, 'tag') == '手持身份证半人照') {
                $picUrlHand = data_get($pic, 'url', '');
            }
        }

        return [
            'name' => $name,
            'id_num' => $idNum,
            'back_url' => $picUrlBack,
            'face_url' => $picUrlFace,
            'hand_url' => $picUrlHand,
        ];
    }

    public function delivery($orderId, $trackingNum, $trackingCompanyId)
    {
        info('天猫准备发货', [func_get_args()]);
        $c = new AgisoClient($this->shopName);
        if ($trackingNum == '无需物流' || $trackingCompanyId == '1000') {
            $r = $c->deliveryVirtual($orderId);
            $j = json_decode($r, 1);
            if (!data_get($j, 'IsSuccess', false)) {
                throw new \LogicException('发货异常'.data_get($j, 'Error_Msg', ''), 100);
            }
            return true;
        }
        $trackingCompanyCode = data_get(collect(config('plan-market.logistics_companies'))->where('id', $trackingCompanyId)
            ->first(), 'tmall_company', '');
        info('天猫准备发货参数', [$orderId,$trackingCompanyId,$trackingCompanyCode]); 
        $r = $c->delivery($orderId, $trackingCompanyCode, $trackingNum);
        info('agiso发货返回值', [$orderId, $r]);
        $j = json_decode($r, 1);
        if (!data_get($j, 'IsSuccess', false)) {
            if(data_get(data_get($j,'Data',[]),'ErrCode')=='B150'){
                throw new \LogicException('天猫发货请求存在并发情况',414);
            }
            throw new \LogicException('发货异常'.data_get($j, 'Error_Msg', ''), 100);
        }
        info('天猫用agiso发货成功！', [func_get_args()]);
        return true;
        $r   = $this->client->fetchDeliveryInfo($orderId);
        $dom = new \simple_html_dom();
        $dom->load($r);

        $params = [
            "_fmw.r._0.count" => " 320412",
            "_fmw.r._0.c"     => " 李国超",
            "_fmw.r._0.p"     => " 江苏省",
            "_fmw.r._0.ci"    => " 常州市",
            "_fmw.r._0.d"     => " 武进区",
            "_fmw.r._0.to"    => "",
            "_fmw.r._0.i"     => " false",
            "_fmw.r._0.di"    => " 320412",
            "_fmw.r._0.coun"  => "",
            "_fmw.r._0.adr"   => " 高新区   光宝宿舍餐厅代收",
            "_fmw.r._0.dd"    => " 江苏省常州市武进区 高新区   光宝宿舍餐厅代收",
            "_fmw.r._0.ad"    => " 江苏省^^^常州市^^^武进区^^^ 高新区   光宝宿舍餐厅代收",
            "_fmw.r._0.z"     => " 000000",
            "_fmw.r._0.ddd"   => "",
            "_fmw.r._0.ph"    => "",
            "_fmw.r._0.b"     => "",
            "_fmw.r._0.t"     => "",
            "_fmw.r._0.mo"    => " 15269048636",
            "_fmw.f._0.co"    => " 1375567752",
            "_fmw.f._0.coun"  => " 370613",
            "_fmw.f._0.c"     => " 落基伟业",
            "_fmw.f._0.p"     => "",
            "_fmw.f._0.ci"    => "",
            "_fmw.f._0.cou"   => "",
            "_fmw.f._0.adr"   => " 观海路富夼街37号",
            "_fmw.f._0.dd"    => " 山东省烟台市莱山区   观海路富夼街37号",
            "_fmw.f._0.ad"    => " 山东省^^^烟台市^^^莱山区^^^   观海路富夼街37号",
            "_fmw.f._0.z"     => " 264002",
            "_fmw.f._0.ddd"   => "",
            "_fmw.f._0.ph"    => "",
            "_fmw.f._0.b"     => "",
            "_fmw.f._0.t"     => "",
            "_fmw.f._0.m"     => " 15688510010",
            "orderId"         => " 140744444814",

        ];

        foreach ($params as $k => $v) {
            $params[$k] = urlencode(data_get($dom->find('input[name="' . $k . '"]', 0), 'value', ''));
        }


        $params["mailNo"]      = $trackingNum;
        $params["companyCode"] = $trackingCompanyCode;
        $params2               = [
            "source"                                  => "",
            "callUrl"                                 => "",
            "_tb_token_"                              => "",
            "mailNo"                                  => "",
            "companyCode"                             => "",
            "orderId"                                 => "",
            "tradeId"                                 => "",
            "taobaoTradeId"                           => "",
            "branchName"                              => "",
            "branchCode"                              => "",
            "courierName"                             => "",
            "courierMobile"                           => "",
            "courierId"                               => "",
            "cpName"                                  => "",
            "receiverDetail"                          => "",
            "receiverZipCode"                         => "",
            "receiverProvince"                        => "",
            "receiverCity"                            => "",
            "receiverDistrict"                        => "",
            "receiverContactName"                     => "",
            "receiverTown"                            => "",
            "receiverPhone"                           => "",
            "receiverTelePhone"                       => "",
            "receiverMobilePhone"                     => "",
            "fetcherContactName"                      => "",
            "fetcherPhone"                            => "",
            "fetcherMobilephone"                      => "",
            "addressFull"                             => "",
            "fetcherZipCode"                          => "",
            "isOverSea"                               => "",
            "flag"                                    => "",
            "forwardFlag"                             => "",
            "province"                                => "",
            "action"                                  => "",
            "event_submit_do_online_consign"          => "",
            "event_submit_do_offline_consign"         => "",
            "event_submit_do_nosheet_consign"         => "",
            "event_submit_do_dummy"                   => "",
            "event_submit_do_guo_guo_consign"         => "",
            "event_submit_ajax_guo_guo_create_order"  => "",
            "event_submit_do_cod_consign"             => "",
            "event_submit_do_store_consign"           => "",
            "event_submit_do_refresh_address"         => "",
            "event_submit_do_refresh_store"           => "",
            "event_submit_do_store_cod_consign"       => "",
            "event_submit_do_refresh_address_ensured" => "",
            "event_submit_do_submit_oversea"          => "",
            "isFreshUser"                             => "",
            "J_SetUrl"                                => "",
            "offlineNewFlag"                          => "",
            "companyId"                               => "",
            "_fmw.r._0.count"                         => "",
            "_fmw.r._0.c"                             => "",
            "_fmw.r._0.p"                             => "",
            "_fmw.r._0.ci"                            => "",
            "_fmw.r._0.d"                             => "",
            "_fmw.r._0.to"                            => "",
            "_fmw.r._0.i"                             => "",
            "_fmw.r._0.di"                            => "",
            "_fmw.r._0.coun"                          => "",
            "_fmw.r._0.adr"                           => "",
            "_fmw.r._0.dd"                            => "",
            "_fmw.r._0.ad"                            => "",
            "_fmw.r._0.z"                             => "",
            "_fmw.r._0.ddd"                           => "",
            "_fmw.r._0.ph"                            => "",
            "_fmw.r._0.b"                             => "",
            "_fmw.r._0.t"                             => "",
            "_fmw.r._0.mo"                            => "",
            "splitFlag"                               => "",
            "orderGoodsListSize"                      => "",
            "_fmw.n._0.g"                             => "",
            "_fmw.f._0.co"                            => "",
            "_fmw.f._0.coun"                          => "",
            "_fmw.f._0.c"                             => "",
            "_fmw.f._0.p"                             => "",
            "_fmw.f._0.ci"                            => "",
            "_fmw.f._0.cou"                           => "",
            "_fmw.f._0.adr"                           => "",
            "_fmw.f._0.dd"                            => "",
            "_fmw.f._0.ad"                            => "",
            "_fmw.f._0.z"                             => "",
            "_fmw.f._0.ddd"                           => "",
            "_fmw.f._0.ph"                            => "",
            "_fmw.f._0.b"                             => "",
            "_fmw.f._0.t"                             => "",
            "_fmw.f._0.m"                             => "",
            "_fmw.re._0.co"                           => "",
            "_fmw.re._0.coun"                         => "",
            "_fmw.re._0.c"                            => "",
            "_fmw.re._0.p"                            => "",
            "_fmw.re._0.ci"                           => "",
            "_fmw.re._0.cou"                          => "",
            "_fmw.re._0.adr"                          => "5",
            "_fmw.re._0.dd"                           => "",
            "_fmw.re._0.ad"                           => "",
            "_fmw.re._0.z"                            => "",
            "_fmw.re._0.ddd"                          => "",
            "_fmw.re._0.ph"                           => "",
            "_fmw.re._0.b"                            => "",
            "_fmw.re._0.t"                            => "",
            "_fmw.re._0.m"                            => "",
            "initialWeightOld"                        => "",
            "_fmw.f._0.f"                             => "",
            "_fmw.f._0.fe"                            => "",
            "_fmw.f._0.fet"                           => "",
            "companyName"                             => "",

        ];
        $str                   = '';
        foreach ($params2 as $k => $v) {
            $params2[$k] = urlencode(iconv('utf8', 'gb2312//IGNORE', data_get($dom->find('input[name="' . $k . '"]', 0), 'value', '')));
            if ($k == 'companyName') {
                $params2[$k] = '%C7%EB%CA%E4%C8%EB%CE%EF%C1%F7%B9%AB%CB%BE%C3%FB%B3%C6';
            }
            if ($k == 'event_submit_do_offline_consign') {
                $params2[$k] = '1';
            }

            if ($k == '_fmw.r._0.mo') {
                $params2[$k] = urlencode(iconv('utf8', 'gb2312//IGNORE', data_get($dom->find('input[name="receiverMobilePhone"]', 0), 'value', '')));
            }

            if ($k == '_fmw.n._0.g') {
                $params2[$k] = '%C4%FA%BF%C9%D2%D4%D4%DA%B4%CB%CA%E4%C8%EB%B1%B8%CD%FC%D0%C5%CF%A2%A3%A8%BD%F6%C2%F4%BC%D2%D7%D4%BC%BA%BF%C9%BC%FB%A3%A9%A1%A3';
            }
        }

        $params2["mailNo"]      = $trackingNum;
        $params2["companyCode"] = $trackingCompanyCode;
        $params2["tradeId"]     = urlencode("\${taobaoTradeId}");
        if ($trackingNum == '无需物流' || $trackingCompanyId == '1000') {
            $params2["mailNo"]      = '';
            $params2["companyCode"] = '';
            $params2["offlineNewFlag"] = '0';
            $params2["event_submit_do_dummy"] = '1';
            unset($params2["event_submit_do_offline_consign"]);
        }
        $r = $this->client->delivery($params);

        info('params', [$params, $params2]);
        if (trim($r) != '{"success":true,"result":0,"msg":""}') {
            error('天猫发货第一步异常', [$orderId, $trackingCompanyId, $trackingNum, $params, $r]);
            throw new \LogicException('发货异常', 100);
        }
        foreach ($params2 as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }

        $str = substr($str, 0, strlen($str) - 1);
        $r   = $this->client->deleveryByOrderId($orderId, $str);
        if (!empty($r)) {
            error('天猫发货第二步异常', [func_get_args(), $r]);
            throw new \LogicException('发货异常', 200);
        }
        info('天猫发货成功！', [func_get_args()]);
        return true;
    }

    public function updateSellerMemo($orderId, $flag=0, $memo)
    {
        info('天猫更新备注', [func_get_args()]);
        $c = new AgisoClient($this->shopName);
        $memo = str_replace('</br>', '', $memo);
        $c->updateMemo($orderId, $memo, $flag);
        return true;
        $r = $this->client->sellerAdmin();
        $dom = new \simple_html_dom();
        $dom->load($r);
        $tbToken = data_get($dom->find('input[id="_tb_token_"]', 0), 'value', '');
        
        $this->client->updateSellerMemo($orderId, $tbToken, (string)$flag, urlencode(iconv('utf8', 'gbk//IGNORE', $memo)));
        return true;
    }

    public function fetchSellerMemo($orderId)
    {
        $r = $this->client->fetchSellerMemo($orderId);
        if (strpos($r, '手机扫码，安全登录')) {
            throw new \LogicException('cookie失效', 202);
        }
        $j = json_decode($r, 1);
        $memo = data_get($j, 'tip', '');
        return [
            'memo' => $memo,
        ];
    }

    public function fetchShopInfo($cookie)
    {
        $r = $this->client->sellerAdmin();

        $dom = new \simple_html_dom();
        $dom->load($r);
        $tbToken = data_get($dom->find('input[id="_tb_token_"]', 0), 'value', '');
//        $r = TmallClient::fetchSellerCenter($cookie);
//        preg_match('/mainUserId=([\d]{10});/', $r, $arr);
//        $mainShopId = data_get($arr, '1', '');
//
        $r = TmallClient::fetchPersonInfo($tbToken, $cookie);
        $j = json_decode($r, 1);
        return $j;
    }

    /**
     * 追加memo
     * @param int $order_id
     * @param string $rocky_memo
     * @return mixed|string
     */
    function endMemo($order_id=0,$rocky_memo=''){
        //获取京东的memo
        $jd_memo = data_get($this->fetchSellerMemo($order_id),'memo');
        $jd_memo = str_replace('暂时没有标记信息', '', $jd_memo);
        //初次添加<<<** memo **>>>
        if (strpos($jd_memo,'《')===false||strpos($jd_memo,'》')===false){
            $rocky_memo = '《'.$rocky_memo. '》';
            $end_memo = $jd_memo.$rocky_memo;
        }else{//后续加<<<** memo **>>>
            $end_memo = str_replace('》',$rocky_memo. ' 》',$jd_memo);
        }

        if (substr_count($rocky_memo, '@') == '2') {
            $end_memo = $end_memo.'@'.str_shell($rocky_memo, '@', '@').'@';
        }

        return $end_memo;//拼接好的memo
    }

    /**
     * @param int $order_id
     * @param string $rocky_memo
     * @return mixed|string
     * 替换更新
     */
    function insertMemo($order_id=0,$rocky_memo='',$flag='-1'){
        //获取京东的memo
        $jd_memo = data_get($this->fetchSellerMemo($order_id),'memo','');
        $jd_memo = str_replace('暂时没有标记信息', '', $jd_memo);
        //初次添加<<<** memo **>>>
        if (strpos($jd_memo,'《')===false||strpos($jd_memo,'》')===false){
            $rocky_memo = '《'.$rocky_memo. '》';
            $end_memo = $jd_memo.$rocky_memo;
        }else{//后续加<<<** memo **>>>
            $start = strlen('《')+strpos($jd_memo,'《');
            $memo  = substr($jd_memo,$start);
            $end   = strstr($memo,'》');
            $memo  = str_replace($end,'',$memo);
            $end_memo = $memo!=''?str_replace($memo,$rocky_memo,$jd_memo):str_replace('《》','《'.$rocky_memo. '》',$jd_memo);
        }
        //return $end_memo;//拼接好的memo
        $this->updateSellerMemo($order_id,$flag,$end_memo);
    }

    public function refetchOrder($orderId)
    {
        info('天猫准备补抓订单', [$orderId]);
        $c = new AgisoClient($this->shopName);
        $r = $c->orderDetail($orderId);
        $j = json_decode($r, 1);
        $jsonArr = data_get($j, 'Data', []);
        $source = 'tmall-' . data_get($jsonArr, 'SellerNick');
        $createdAt = data_get($jsonArr, 'PayTime', '');
        $nickname = data_get($jsonArr, 'BuyerNick', '');
        $flag = data_get($jsonArr, 'SellerFlag', '');
        $sourceId = data_get($jsonArr, 'Tid', '');

        $data = [
            'source' => $source,
            'created_at' => $createdAt,
            'real_source_id' => (string)$sourceId,
            'nickname' => $nickname,
            'flag' => $flag,
            'action' => 'orderDetail',
        ];

        $outerOrders = data_get($jsonArr, 'Orders', []);
        $k = 1;
        $return = [];
        if (!empty($outerOrders)){
            foreach ($outerOrders as $outerOrder) {
                $sku = data_get($outerOrder, 'OuterSkuId', '');
                $perProductNum = data_get($outerOrder, 'Num', '');
                for ($i = 1; $i <= $perProductNum; $i++) {
                    $data['sku'] = $sku;
                    if (count($outerOrders) > '1' || $perProductNum > '1') {
                        $data['order_id'] = $sourceId . '-C' . $k;
                    } else {
                        $data['order_id'] = $sourceId;
                    }
                    $planOrderPage = PlanOrderPages::where('fetch_code', '=', $sku)
                        ->where('status', '=', '100')
                        ->first();
                    if (empty($planOrderPage)) {
                        if ($k <= '0') {
                            $return = [];
                        }
                        $return[$k] = $sku . '产品不存在'.$orderId;
                        continue;
                    }
                    $isDis = dispatch((new \App\Jobs\PlanOrderCreate($data))->onQueue('plan_order_create'));
                    $k++;
                }
            }
        }else{
            info('补抓订单不存在',[$orderId,$this->shopName,$j]);
        }

        info('天猫补抓订单', $return);
    }
}